package bat.iog.hytool.nio.demo1;


import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NioClientMain {

    private static final ExecutorService executorService = Executors.newFixedThreadPool(5);

    public static void main(String[] args) {
        NioClientMain nioClientMain = new NioClientMain();
        nioClientMain.startClient(7809);
    }

    public void startClient(int port) {
        try {
            //打开socket通道
            SocketChannel sc = SocketChannel.open();
            //设置非阻塞
            sc.configureBlocking(false);
            //连接到服务器-指定主机名称和端口
            sc.connect(new InetSocketAddress(InetAddress.getLocalHost(), port));
            //打开选择器
            Selector selector = Selector.open();
            //注册到服务器上的socket动作
            sc.register(selector, SelectionKey.OP_CONNECT);
            executorService.execute(new ClientReadThread(selector));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


